//
//  MainSubNewsViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/10/19.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "MainSubNewsViewModel.h"

#import "NewsTableViewModel.h"

@implementation MainSubNewsViewModel

- (void)initialize
{
    [super initialize];
    
    @weakify(self);
    
    _tabIndex = 0;
    
    DataManager* dm = [DataManager sharedDataManager];
    self.provinceListData = dm.locationPLData;
    
    NSMutableArray* newTableVMS = [NSMutableArray array];
    for (NSInteger index=0; index<2; index++)
    {
        NewsTableViewModel* tvm = [[NewsTableViewModel alloc] initWithParams:@{}];
        tvm.perPage = List_PageSize;
        tvm.lastPage = 1000;
        tvm.cellHeight = 94;
        /// 允许下拉刷新
        tvm.shouldPullDownToRefresh = YES;
        /// 允许上拉加载
        tvm.shouldPullUpToLoadMore = YES;
        tvm.isReplace = NO;
        tvm.cateID = HCStrFormat(@"%d", (int)(56+index));
        tvm.tag = 10+index;
        
        newTableVMS[newTableVMS.count] = tvm;
    }
    self.tableVMs = newTableVMS;
    
    [[RACObserve(self, tabIndex) distinctUntilChanged] subscribeNext:^(id x) {
        @strongify(self)
        
        //判断当前是否需要请求数据
        NSInteger curTabIndex = [x integerValue];
        
        NewsTableViewModel* curTVM = self.tableVMs[curTabIndex];
        
        if (curTVM.dataSource.count == 0)
        {
            [curTVM.requestDataCmd execute:@{@"LoadIndex":@0}];
        }
    }];
    
    // 通知
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:Notify_FirstPageReload object:nil] subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSNotification* notification = x;
         
         self.provinceListData = notification.object;
     }];
    
    // 地区
    [[RACObserve(self, provinceListData) takeUntil:[self rac_willDeallocSignal]] subscribeNext:^(id x)
     {
         @strongify(self);
         
         for (NewsTableViewModel* vm in self.tableVMs)
         {
             vm.areaID = self.provinceListData ? self.provinceListData.areaID : @"0";
             [vm.requestDataCmd execute:@{@"LoadIndex":@0}];
         }
     }];
}

@end
